from service import hr_service as hr
from entity import organizations as o
from service import recongnize_service as rs
import os
import cv2
import numpy as np

PATH = os.getcwd() + "\\data\\"
PIC_PATH = PATH + "faces\\"
DATA_FILE = PATH + "employee_data.txt"
WORK_TIME = PATH + "work_time.txt"
USER_PASSWORD = PATH + "user_password.txt"
RECORD_FILE = PATH + "lock_record.txt"
IMG_WIDTH = 640
IMG_HEIGHT = 480

# 自检，检查默认文件缺失
def checking_data_files():
    """
    自检文件是否缺失
    :return: None
    """
    if not os.path.exists(PATH):
        os.mkdir(PATH)
        print("数据文件夹丢失，已重新创建：" + PATH)
    if not os.path.exists(PIC_PATH):
        os.mkdir(PIC_PATH)
        print("照片文件夹丢失，已重新创建：" + PIC_PATH)
    sample1 = PIC_PATH + "1000000000.png"  # 样本1文件路径
    if not os.path.exists(sample1):
        sample_img_1 = np.zeros((IMG_HEIGHT, IMG_WIDTH, 3), np.uint8)  # 创建一个空内容图像
        sample_img_1[:, :, 0] = 255  # 改为纯蓝图像
        cv2.imwrite(sample1, sample_img_1)  # 保存此图像
        print("默认样本1已补充")
    sample2 = PIC_PATH + "2000000000.png"  # 样本2文件路径
    if not os.path.exists(sample2):
        sample_img_2 = np.zeros((IMG_HEIGHT, IMG_WIDTH, 3), np.uint8)  # 创建一个空内容图像
        sample_img_2[:, :, 1] = 255  # 改为纯蓝图像
        cv2.imwrite(sample2, sample_img_2)  # 保存此图像
        print("默认样本2已补充")
    if not os.path.exists(DATA_FILE):
        open(DATA_FILE, "a+")  # 附加读写方式打开文件，达到创建空文件目的
        print("员工信息文件丢失，已重新创建：" + DATA_FILE)
    if not os.path.exists(RECORD_FILE):
        open(RECORD_FILE, "a+")  # 附加读写方式打开文件，达到创建空文件目的
        print("打卡记录文件丢失，已重新创建：" + RECORD_FILE)
    if not os.path.exists(USER_PASSWORD):
        file = open(USER_PASSWORD, "a+", encoding="utf-8")  # 附加读写方式打开文件，达到创建空文件目的
        user = dict()
        user["mr"] = "mrsoft"
        file.write(str(user))  # 将默认管理员账号密码写入到文件中
        file.close()  # 关闭文件
        print("管理员账号密码文件丢失，已重新创建：" + RECORD_FILE)
    if not os.path.exists(WORK_TIME):
        file = open(WORK_TIME, "a+", encoding="utf-8")  # 附加读写方式打开文件，达到创建空文件目的
        file.write("09:00:00/17:00:00")  # 将默认时间写入到文件中
        file.close()  # 关闭文件
        print("上下班时间配置文件丢失，已重新创建：" + RECORD_FILE)


def load_employee_info():
    """
    加载员工数据
    将文件中的内容逐行读取，通过英文逗号隔开，根据分割出的数据创建员工对象，然后把员工对象保存再员工列表中
    :return: None
    """
    max_id = 1
    file = open(DATA_FILE, "r", encoding="utf-8")
    for line in file.readlines():
        id,name,code = line.rstrip().split(",")
        o.add(o.Employee(id, name, code))
        if int(id) > max_id:
            max_id = int(id)
    o.MAX_ID = max_id
    file.close()


def load_lock_record() -> None:
    """
    载入所有打卡记录
    :return: None
    """
    file = open(RECORD_FILE, "r", encoding="utf-8")
    text = file.read()
    if len(text) >0:
        o.LOCK_RECORD = eval(text)
        file.close()


# 加载员工图像
def load_employee_pic() -> None:
    """
    加载员工照片并训练人脸识别模型
    :return: None
    """
    photos = list()  # 样本图像列表
    lables = list()  # 标签列表
    pics = os.listdir(PIC_PATH)  # 读取所有照片
    if len(pics) != 0:  # 如果照片文件不是空的
        for file_name in pics:  # 遍历所有图像文件
            code = file_name[0:o.CODE_LEN]  # 截取文件名开头的特征码
            photos.append(cv2.imread(PIC_PATH + file_name, 0))  # 以灰度图像的方式读取样本
            lables.append(int(code))  # 样本的特征码作为训练标签
        rs.train(photos, lables)  # 识别器训练样本
    else:  # 不存在任何照片
        print("Error >> 员工照片文件丢失，请重新启动程序并录入员工信息！")


def load_work_time_config():
    """
    加载上下班时间数据
    :return: None
    """
    file = open(WORK_TIME, "r", encoding="utf-8")
    text = file.read().rstrip()
    times = text.split("/")
    o.WORK_TIME = times[0]
    o.CLOSING_TIME = times[1]
    file.close()


def load_users():
    """
    加载管理员账号和密码
    :return: None
    """
    file = open(USER_PASSWORD, "r", encoding="utf-8")
    text = file.read()
    if len(text) >0:
        o.USERS = eval(text)
    file.close()


def save_employee_all() -> None:
    """
    将员工信息持久化
    将所有员工信息持久化保存到数据文件中。
    :return: None
    """
    file = open(DATA_FILE, "w", encoding="utf-8")
    info = ""
    for emp in o.EMPLOYEES:
        info += str(emp.id) + "," + str(emp.name) + "," + str(emp.code) + "\n"
    file.write(info)
    file.close()


def save_lock_record() -> None:
    """
    将打卡记录持久化
    :return: None
    """
    file = open(RECORD_FILE, "w", encoding="utf-8")
    info = str(o.LOCK_RECORD)
    file.write(info)
    file.close()


def save_work_time_config():
    """
    将上下班时间写到文件中
    :return: None
    """
    file = open(WORK_TIME, "w", encoding="utf-8")
    times = str(o.WORK_TIME) + "/" + str(o.CLOSING_TIME)
    file.write(times)
    file.close()


def remove_pics(id: str) -> None:
    """
    删除指定员工的所有照片
    :param id: 员工的ID
    :return: None
    """
    pics = os.listdir(PIC_PATH)
    code = str(hr.get_code_with_id(id))
    for file_name in pics:
        if file_name.startswith(code):
            os.remove(PIC_PATH + file_name)
            print("删除照片：" + file_name)


def create_CSV(file_name, text):
    file = open(PATH + file_name + ".csv", "w", encoding="gbk")
    file.write(text)
    file.close()
    print("csv文件生成")